package jt.classic.app.dms;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import jt.classic.system.AbstractSimpleManager;
import jt.classic.system.ISystem;
import jt.classic.system.ISystemException;
import jt.classic.system.object.IObject;
import jt.classic.system.object.ObjectManager;
import jt.classic.system.purview.PurviewManager;
import jt.classic.system.user.IUser;


/**
 * 文档共享设置管理器
 *
 * @author mido
 *
 */
public class DmsSharedManager extends AbstractSimpleManager {
    /**
    * 构造函数
    * @param conn
    */
    public DmsSharedManager() {
        super();
    }

    /**
    * 构造函数
    * @param conn
    */
    public DmsSharedManager(Connection conn) {
        super(conn);
    }

    /**
     * 用户可访问的文件夹
     * <p>不包含用户自己创建的文件夹</p>
     * @param user 用户实例
     * @param parentid 父节点ID
     * @return List
     * @throws ISystemException
     */
    public List<TreeNode> getChildrenFolder(IUser user, String parentid)
        throws ISystemException {
        List<TreeNode> nodeList = new ArrayList<TreeNode>();

        /*根节点*/
        if (parentid.equals("-1")) {
            String purviewSql = ObjectManager.getObjectPurviewSQL("FOLDER",
                    user, 0, ">=");

            String sql = "select isys_object.OBJ_CREATORNAME,doc_hgbgodkqxb.PK_DOC_HGBGODKQXB, doc_hgbgodkqxb.COL_FOLDERNAME, doc_hgbgodkqxb.COL_PARENTFOLDERID FROM doc_hgbgodkqxb " +
                "Inner Join isys_object_relation ON doc_hgbgodkqxb.PK_DOC_HGBGODKQXB = isys_object_relation.OBJ_PKID " +
                "and isys_object_relation.OBJ_TABLE='DOC_HGBGODKQXB' Inner Join isys_object ON isys_object.ID = isys_object_relation.ID " +
                "Inner Join (" + purviewSql +
                ") C ON isys_object.ID = C.OBJ_ID" +
                " where isys_object.OBJ_CREATORID <> '" + user.id() +
                "'   and doc_hgbgodkqxb.COL_PARENTFOLDERID = '" + parentid +
                "' order by isys_object.OBJ_KEY desc,OBJ_CREATETIME";

            List<Map> objList = this.trimmer.searchMultiData(sql);

            for (Map info : objList) {
                if (info != null) {
                    TreeNode node = this.initTreeNode(info, user);

                    nodeList.add(node);
                }
            }
        } else {
            String sql = "SELECT * FROM DOC_HGBGODKQXB WHERE COL_PARENTFOLDERID = " +
                parentid;

            List list = this.trimmer.searchMultiData(sql);

            if ((list != null) && !list.isEmpty()) {
                ObjectManager om = new ObjectManager(this.conn);
                PurviewManager pm = new PurviewManager(this.conn);

                for (int i = 0; i < list.size(); i++) {
                    Map info = (Map) list.get(i);

                    String pkid = (String) info.get("PK_DOC_HGBGODKQXB");

                    IObject obj = om.getObjectShellByRelation("DOC_HGBGODKQXB",
                            pkid);

                    int purview = pm.purview(obj.id(), obj.ikey(), user);

                    /*没有直接进行授权*/
                    if (purview == -2) {
                        /*继承父级节点权限(并且权限 > -1)*/
                        if (this.parentInheritPurview(pkid, user)) {
                            info.put("OBJ_CREATORNAME", obj.icreatorname());

                            TreeNode node = this.initTreeNode(info, user);

                            nodeList.add(node);
                        }
                    } else if (purview > -1) {
                        info.put("OBJ_CREATORNAME", obj.icreatorname());

                        TreeNode node = this.initTreeNode(info, user);

                        nodeList.add(node);
                    }
                }
            }
        }

        return nodeList;
    }

    /**
     * 校验文件夹继承权限(父级文件夹,不包含当前文件夹)
     * @param id 文件夹ID
     * @param user 用户
     * @return boolean
     */
    public boolean parentInheritPurview(String id, IUser user) {
        String purviewSql = ObjectManager.getObjectInheritPurviewSQL("FOLDER",
                user, 0, ">=");

        String sql = "SELECT PARENTID FROM DOC_FILERELATION Inner Join isys_object_relation ON PARENTID = isys_object_relation.OBJ_PKID " +
            "and isys_object_relation.OBJ_TABLE='DOC_HGBGODKQXB' Inner Join (" +
            purviewSql +
            ") C ON isys_object_relation.ID = C.OBJ_ID WHERE DOC_FILERELATION.FID = " +
            id +
            " AND DOC_FILERELATION.TYPE = 'FOLDER' AND DOC_FILERELATION.LEVEL <> '0' ";

        return this.trimmer.haveMoreData(sql);
    }

    /**
     * 校验文件夹继承权限(包含当前文件夹)
     * @param id 文件夹ID
     * @param user 用户
     * @return boolean
     */
    public boolean InheritPurview(String id, IUser user) {
        boolean rnt = false;

        ObjectManager om = new ObjectManager(this.conn);
        IObject obj = null;

        try {
            obj = om.getObjectShellByRelation("DOC_HGBGODKQXB", id);
        } catch (Exception ex) {
            ISystem.catchException(this, ex);
        }

        int purview = -2;

        /*校验当前文件夹继承权限*/
        PurviewManager pm = new PurviewManager(this.conn);

        if (pm.inherit(obj.id(), obj.ikey())) {
            purview = pm.purview(obj.id(), obj.ikey(), user);
        }

        if (purview < 0) {
            /*校验父级文件夹继承权限*/
            rnt = this.parentInheritPurview(id, user);
        } else {
            rnt = true;
        }

        return rnt;
    }

    /**
     * 文件夹继承权限(父级文件夹,不包含当前文件夹)
     * @param id 文件夹ID
     * @param user 用户
     * @return Map
     */
    public Map parentInheritPurviewMap(String id, IUser user) {
        String purviewSql = ObjectManager.getObjectInheritPurviewSQL("FOLDER",
                user, 0, ">=");

        String sql = "SELECT PURVIEW FROM ISYS_PURVIEW INNER JOIN ( " +
            purviewSql +
            " ) C  ON ISYS_PURVIEW.OBJ_ID = C.OBJ_ID INNER JOIN isys_object_relation ON ISYS_PURVIEW.OBJ_ID = " +
            "isys_object_relation.OBJ_PKID AND isys_object_relation.OBJ_TABLE='DOC_HGBGODKQXB' Inner Join DOC_FILERELATION " +
            "ON DOC_FILERELATION.PARENTID = isys_object_relation.OBJ_PKID AND DOC_FILERELATION.TYPE = 'FOLDER' " +
            "AND DOC_FILERELATION.LEVEL <> '0' AND DOC_FILERELATION.FID = " +
            id;

        return this.trimmer.searchSymmetricalData(sql, "PURVIEW", "PURVIEW");
    }

    /**
     * 文件夹继承权限(包含当前文件夹)
     * @param id 文件夹ID
     * @param user 用户
     * @return Map
     */
    public Map InheritPurviewMap(String id, IUser user) {
        Map purviewMap = null;

        ObjectManager om = new ObjectManager(this.conn);
        IObject obj = null;

        try {
            obj = om.getObjectShellByRelation("DOC_HGBGODKQXB", id);
        } catch (Exception ex) {
            ISystem.catchException(this, ex);
        }

        PurviewManager pm = new PurviewManager(this.conn);

        /*当前文件夹继承权限*/
        if (pm.inherit(obj.id(), obj.ikey())) {
            /*当前文件夹继承权限内容*/
            purviewMap = pm.purview4Map(obj.id(), obj.ikey(), user);
        }

        if (purviewMap != null && !purviewMap.isEmpty()) {
            /*父级文件夹继承权限内容*/
            Map parentPurviewMap = this.parentInheritPurviewMap(id, user);

            if (parentPurviewMap != null) {
                /*聚合文件夹继承权限内容*/
                purviewMap.putAll(parentPurviewMap);
            }
        } else {
            purviewMap = this.parentInheritPurviewMap(id, user);
        }

        return purviewMap;
    }

    /**
     * 初始化TreeNode
     * @param info 节点内容
     * @param user 会话用户
     * @return TreeNode
     */
    private TreeNode initTreeNode(Map info, IUser user) {
        TreeNode node = new TreeNode();

        String pkid = (String) info.get("PK_DOC_HGBGODKQXB");
        node.setId(pkid);

        String pid = (String) info.get("COL_PARENTFOLDERID");
        node.setParentId(pid);

        String text = (String) info.get("COL_FOLDERNAME");
        node.setText(text);

        node.setQtip("授权者: " + (String) info.get("OBJ_CREATORNAME"));

        if (hasChild(user, pkid)) {
            node.setLeaf(false);
        } else {
            node.setLeaf(true);
        }

        // 生成全路径
        if ("-1".equals(pkid)) {
            node.setFullpathId("");
            node.setFullpath("");
        } else {
            DmsManager managre = new DmsManager(this.conn);

            Map pfolder = managre.getFolder(pid);
            StringBuilder path = new StringBuilder();
            StringBuilder ids = new StringBuilder();

            while ((pfolder != null) &&
                    !"-1".equals((String) pfolder.get("PK_DOC_HGBGODKQXB"))) {
                path.insert(0, (String) pfolder.get("COL_FOLDERNAME"));
                path.insert(0, '/');
                ids.insert(0, (String) pfolder.get("PK_DOC_HGBGODKQXB"));
                ids.insert(0, '/');
                pfolder = managre.getFolder((String) pfolder.get(
                            "COL_PARENTFOLDERID"));
            }

            node.setFullpathId(ids.toString());
            node.setFullpath(path.toString());
        }

        return node;
    }

    /**
     * 判断当前节点是否有子节点
     *
     * @param user 用户
     * @param 节点id
     * @return 有子节点则返回true 反之false
     */
    public boolean hasChild(IUser user, String nodeId) {
        boolean rnt = false;

        String sql = "SELECT * FROM DOC_HGBGODKQXB WHERE COL_PARENTFOLDERID = " +
            nodeId;

        List list = this.trimmer.searchMultiData(sql);

        if ((list != null) && !list.isEmpty()) {
            ObjectManager om = new ObjectManager(this.conn);
            PurviewManager pm = new PurviewManager(this.conn);

            for (int i = 0; i < list.size(); i++) {
                Map info = (Map) list.get(i);

                String pkid = (String) info.get("PK_DOC_HGBGODKQXB");

                try {
                    IObject obj = om.getObjectShellByRelation("DOC_HGBGODKQXB",
                            pkid);

                    int purview = pm.purview(obj.id(), obj.ikey(), user);

                    /*没有直接进行授权*/
                    if (purview == -2) {
                        /*继承父级节点权限(并且权限 > -1)*/
                        if (this.parentInheritPurview(pkid, user)) {
                            rnt = true;

                            break;
                        }
                    } else if (purview > -1) {
                        rnt = true;

                        break;
                    }
                } catch (Exception ex) {
                    ISystem.catchException(ex);
                    rnt = true;

                    break;
                }
            }
        }

        return rnt;
    }
}
